﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Yeetop.PayHub.YeePay
{
    /// <summary>
    /// 易宝支付 支付网关
    /// Copyright © Yeetop Inc.(www.yeetop.com)  All rights reserved. 
    /// </summary>
    /// <history>
    /// [JianTao] 2010-01-06 Created 
    /// </history>
    public class YeePayPayment : BasePayment
    {
        public YeePayPayment()
            : base()
        { }

        private YeePayTradeInfo Trade;

        public override void PaySend(MerchantInfo merchant, ITradeInfo trade)
        {
            Trade = (YeePayTradeInfo)trade;
            Merchant = merchant;

            StringBuilder builder = new StringBuilder();
            builder.Append(merchant.Gateway);
            builder.Append("?p0_Cmd=Buy");
            builder.Append("&p1_MerId=");
            builder.Append(Merchant.UID);
            builder.Append("&p2_Order=");
            builder.Append(HttpUtility.UrlEncode(Trade.p2_Order, System.Text.Encoding.GetEncoding("gb2312")));
            builder.Append("&p3_Amt=");
            builder.Append(Trade.p3_Amt);
            builder.Append("&p4_Cur=CNY");
            builder.Append("&p5_Pid=");
            builder.Append(HttpUtility.UrlEncode(Trade.p5_Pid, System.Text.Encoding.GetEncoding("gb2312")));
            builder.Append("&p6_Pcat=");
            builder.Append(HttpUtility.UrlEncode(Trade.p6_Pcat, System.Text.Encoding.GetEncoding("gb2312")));
            builder.Append("&p7_Pdesc=");
            builder.Append(HttpUtility.UrlEncode(Trade.p7_Pdesc, System.Text.Encoding.GetEncoding("gb2312")));
            builder.Append("&p8_Url=");
            builder.Append(HttpUtility.UrlEncode(Trade.p8_Url, System.Text.Encoding.GetEncoding("gb2312")));
            builder.Append("&p9_SAF=");
            builder.Append(Trade.p9_SAF);
            builder.Append("&pa_MP=");
            builder.Append(HttpUtility.UrlEncode(Trade.pa_MP, System.Text.Encoding.GetEncoding("gb2312")));
            builder.Append("&pd_FrpId=");
            builder.Append(Trade.pd_FrpId);
            builder.Append("&pr_NeedResponse=");
            builder.Append(Trade.pr_NeedResponse);
            builder.Append("&hmac=");
            builder.Append(SendSign());

            RedirectToGateway(builder.ToString());
        }

        protected override PayStatus CheckReturnData(CheckBillDelegate checkBill)
        {
            // 通知数据中必须包含的Key，如果没有表示数据可能非法
            string[] checkParma = { "p1_MerId", "r0_Cmd", "r1_Code", "r2_TrxId", "r3_Amt", "r4_Cur", "r6_Order", "hmac" };

            if (!ReceiveData.NotifyData.ContainsKeys(checkParma))
            {
                return PayStatus.ServerDataIllegal;
            }

            if (ReceiveData.NotifyData["hmac"] == NotifySign())
            {
                if (ReceiveData.NotifyData["r1_Code"].Equals("1"))
                {
                    BillInfo bill = new BillInfo();
                    bill.MerchantUID = Merchant.UID;
                    bill.OrderId = ReceiveData.NotifyData["r6_Order"];
                    bill.OrderAmount = ReceiveData.NotifyData["r3_Amt"];
                    bill.PayPlatform = PayPlatformType.YeePay;

                    return checkBill(bill);
                }
                else
                {
                    return PayStatus.Failure;
                }
            }
            else
            {
                return PayStatus.SignError;
            }
        }

        protected override bool CheckNotifyData(CheckUpdateBillDelegate checkUpdateBill)
        {
            // 通知数据中必须包含的Key，如果没有表示数据可能非法
            string[] checkParma = { "p1_MerId", "r0_Cmd", "r1_Code", "r2_TrxId", "r3_Amt", "r4_Cur", "r6_Order", "hmac" };

            if (!ReceiveData.NotifyData.ContainsKeys(checkParma))
            {
                System.Web.HttpContext.Current.Response.Write("error");

                return false;
            }

            PayStatus payStatus;

            if (ReceiveData.NotifyData["hmac"] == NotifySign())
            {
                if (ReceiveData.NotifyData["r1_Code"].Equals("1"))
                {
                    BillInfo bill = new BillInfo();
                    bill.MerchantUID = Merchant.UID;
                    bill.OrderId = ReceiveData.NotifyData["r6_Order"];
                    bill.OrderAmount = ReceiveData.NotifyData["r3_Amt"];
                    bill.PayPlatform = PayPlatformType.YeePay;

                    payStatus = checkUpdateBill(bill);
                }
                else
                {
                    payStatus = PayStatus.Failure;
                }
            }
            else
            {
                payStatus = PayStatus.SignError;
            }

            if (payStatus == PayStatus.Succeed)
            {
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.Write("success");
                System.Web.HttpContext.Current.Response.End();

                return true;
            }
            else
            {
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.Write("error");
                System.Web.HttpContext.Current.Response.End();

                return false;
            }
        }

        public override PayPlatformType PayPlatform
        {
            get { return PayPlatformType.YeePay; }
        }

        protected override string SendSign()
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("Buy");
            builder.Append(Merchant.UID);
            builder.Append(Trade.p2_Order);
            builder.Append(Trade.p3_Amt);
            builder.Append("CNY");
            builder.Append(Trade.p5_Pid);
            builder.Append(Trade.p6_Pcat);
            builder.Append(Trade.p7_Pdesc);
            builder.Append(Trade.p8_Url);
            builder.Append(Trade.p9_SAF);
            builder.Append(Trade.pa_MP);
            builder.Append(Trade.pd_FrpId);
            builder.Append(Trade.pr_NeedResponse);

            return YeePayUtility.HmacSign(builder.ToString(), Merchant.Key);
        }

        protected override string NotifySign()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(ReceiveData.NotifyData["p1_MerId"]);
            builder.Append(ReceiveData.NotifyData["r0_Cmd"]);
            builder.Append(ReceiveData.NotifyData["r1_Code"]);
            builder.Append(ReceiveData.NotifyData["r2_TrxId"]);
            builder.Append(ReceiveData.NotifyData["r3_Amt"]);
            builder.Append(ReceiveData.NotifyData["r4_Cur"]);
            builder.Append(ReceiveData.NotifyData["r5_Pid"]);
            builder.Append(ReceiveData.NotifyData["r6_Order"]);
            builder.Append(ReceiveData.NotifyData["r7_Uid"]);
            builder.Append(ReceiveData.NotifyData["r8_MP"]);
            builder.Append(ReceiveData.NotifyData["r9_BType"]);

            return YeePayUtility.HmacSign(builder.ToString(), Merchant.Key);            
        }
    }
}
